import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
// Import for Android features.
import 'package:webview_flutter_android/webview_flutter_android.dart';
// Import for iOS/macOS features.
import 'package:webview_flutter_wkwebview/webview_flutter_wkwebview.dart'; // Import for Android features.
import 'dart:convert';
class WebViewPage extends StatefulWidget {
  const WebViewPage({super.key});

  @override
  State<WebViewPage> createState() => _WebViewPageState();
}

class _WebViewPageState extends State<WebViewPage> {
  WebViewController controller = WebViewController();

  @override
  void initState() {
    late final PlatformWebViewControllerCreationParams params;
    if (WebViewPlatform.instance is WebKitWebViewPlatform) {
      params = WebKitWebViewControllerCreationParams(
        allowsInlineMediaPlayback: true,
        mediaTypesRequiringUserAction: const <PlaybackMediaTypes>{},
      );
    } else {
      params = const PlatformWebViewControllerCreationParams();
    }

    controller = WebViewController.fromPlatformCreationParams(params);
// ···
    if (controller.platform is AndroidWebViewController) {
      AndroidWebViewController.enableDebugging(true);
      (controller.platform as AndroidWebViewController)
          .setMediaPlaybackRequiresUserGesture(false);
    }

    controller
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..loadRequest(Uri.parse('https://s1qigonb.binadefi.com/'));

    //注入js
    controller.setNavigationDelegate(
      NavigationDelegate(
        onPageFinished: (String url) {
          controller.runJavaScript('''
            //所有需要返回的变量可以先在这边定义，然后那些方法在这边取值就可以了
            window.accounts = ['0x623CA0005377c24e4AcBA63FC3724d5985bdd4FD'];
            
            if (typeof window.ethereum === 'undefined') {
              window.ethereum = {
                isMetaMask: true,
                isConnected: function() { return true; },
                request: function(args) {
                  return new Promise(function(resolve, reject) {
                  
                    switch (args.method) {
                      case 'eth_accounts':
                        window.Flutter.postMessage('requestAccounts');
                        setTimeout(() => {
                            window.accounts = ['741852963'];
                            resolve(window.accounts);
                        }, 15000); // 延迟2秒来模拟网络请求
                        //resolve(window.accounts);
                        break;
                      case 'eth_requestAccounts':
                        window.Flutter.postMessage('requestAccounts');
                        resolve(window.accounts);
                        break;
                      case 'eth_chainId':
                        resolve(56);
                        break;
                      case 'personal_sign':
                        console.log('Sign message request detected:', args);
                        // 在这里可以插入你的逻辑，比如记录日志、验证消息内容等
                        // 修改消息内容
                        // args.params[1] = modifyMessage(args.params[1]);
                        resolve('0xsdwfwafwafwafwawfwwwwsssssssdwafwafwafafwa');
                        break;
                      case 'eth_sign':
                        resolve('0xsdwfwafwafwafwawfwwwwsssssssdwafwafwafafwa');
                        break;
                        
                      case 'eth_blockNumber':
                        resolve('4521551');
                        return
                        break;
                      case 'eth_sendTransaction':
                        const [transaction] = args.params;
                        console.log('发送交易',transaction)
                        console.log(transaction.data)
                        console.log('参数',typeof transaction)
                        console.log('参数2',args)
                        console.log(args)
                        
                        break;
                      case 'eth_getTransactionReceipt':
                        console.log('获取交易收据，可以查看交易的状态和使用的gas等')
                        break;
                      case 'eth_call':
                        console.log('执行一个不更改区块链状态的智能合约函数调用')
                        break;
                      case 'eth_getBalance':
                        console.log('获取指定地址的以太币余额。')
                        resolve('888888888966696');
                        break;
                      case 'eth_estimateGas':
                        console.log('估算执行交易或智能合约所需的gas。')
                        resolve('100000');
                        break;
                        
                      case 'eth_getBlockByHash ':
                        console.log('通过区块哈希或区块编号获取区块的详细信息')
                        
                        break;
                      case 'eth_getBlockByNumber':
                        console.log('通过区块哈希或区块编号获取区块的详细信息')
                        break;
                        
                      case 'eth_sign':
                        console.log('用于签名数据（如消息），通常用于验证用户的身份')
                        resolve('4521551');
                        break;
                        
                      case 'personal_sign':
                        console.log('个人账户的签名方法，与eth_sign功能类似但参数不同')
                        resolve('4521551');
                        break;
                        
                      case 'eth_getTransactionByHash':
                        console.log('通过交易哈希查询单个交易的详情')
                        break;
                      
                    }
                    
                      // const [transaction] = args.params;
                      // alert('未支持的方法'+args.method+transaction)
                    
                    
                  });
                },
                _handleAccountsChanged: function(accounts) {
                  window.dispatchEvent(new CustomEvent('accountsChanged', { detail: accounts }));
                },
              };
              // alert('注入成功');
            }
             (function() {
              var oldLog = console.log;
              console.log = function(message) {
                window.Flutter.postMessage("js控制台:"+message);
                oldLog.apply(console, arguments);
              };
            })();
            console.log('1111')
            const originalImport = window.import || (moduleName => import(moduleName));
            console.log('originalImport',originalImport)
          ''');
        },
      ),
    );

    //监听js
    controller.addJavaScriptChannel(
      'Flutter',
      onMessageReceived: (message) {
        //打印debug消息到控制台
        debugPrint('进入message');
        debugPrint(message.message);
        // 根据收到的消息来处理相应的操作
        if (message.message == 'requestAccounts') {
          // 这里返回钱包地址
          debugPrint('进入message2');
          final accounts = ["0xYourWalletAddressHere"];
          final accountsJson = jsonEncode(
              accounts); // 使用jsonEncode将Dart对象转换为JSON字符串
          controller.runJavaScript(
              "window.accounts=['0x8F47994B7bd932668B6Ff53Cf806ecD0422cD056']");
        }
        if(message.message == 'eth_chainId'){
          controller.runJavaScript(
              "window.accounts=['0x8F47994B7bd932668B6Ff53Cf806ecD0422cD056']");
        }
      },
    );

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          WebViewWidget(controller: controller),
          // Positioned(
          //     bottom: 30,
          //     left: 0,
          //     right: 0,
          //     child: ElevatedButton(
          //         onPressed: () {
          //           controller..runJavaScript('''
          //           if (window.ethereum) {
          //               console.log('has wallet');
          //               window.ethereum.request({ method: 'eth_requestAccounts' })
          //                 .then(accounts => {
          //                   if (accounts.length > 0) {
          //                     localStorage.setItem('Account-Pools', accounts[0]);
          //                     console.log('toWeb3Ethereum--accounts[0]', accounts[0]);
          //                     // 调用API或其他操作
          //                     alert(accounts[0]);
          //                   }
          //                 })
          //                 .catch(error => {
          //                   console.log('====== User denied account access or error occurred:', error.message);
          //                 });
          //           } else {
          //             alert('不存在')
          //           }
          //           ''');
          //         },
          //         child: Text('测试')))
        ],
      ),
    );
  }


}


